/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import facade.InversorFacadeLocal;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import entity.Inversor;
import java.util.List;
import javax.persistence.PersistenceContext;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author ari
 */
@Stateless
public class BeanInversor implements BeanInversorRemote {
    private static final Logger logger = Logger.getLogger("BolsaValor");
 
    @EJB
    private InversorFacadeLocal inversorFacade;
    @PersistenceContext(unitName = "BolsaValor-ejbPU")
    private EntityManager em;
        
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

    @Override
    public boolean isUsuario(String login, String clave) {
        
        List<Inversor> invs = em.createQuery("SELECT i FROM Inversor i WHERE i.login = :login AND i.clave = :clave", Inversor.class)
                .setParameter("login", login)
                .setParameter("clave", clave)
                .getResultList();
        
        if(invs.isEmpty())
            return false;
        
        logger.log(Level.INFO, "Usuario logeado: {0} ", login);

        return true;
    }

    @Override
    public boolean registrarUsuario(String login, String clave) {
        
        List<Inversor> invs = em.createQuery("SELECT i FROM Inversor i WHERE i.login = :login", Inversor.class)
                .setParameter("login", login)
                .getResultList();
        
        if(!invs.isEmpty()) // Ya existe un usuario con ese login
            return false;

        Inversor inv = new Inversor();
        inv.setLogin(login);
        inv.setClave(clave);
        
        inversorFacade.create(inv);
            
        if(em.contains(inv))
            return true;
        
        em.flush();
        
        // No se creo
        return false;
        
    }
    
}
